import qs from 'qs'
import { useUserStore } from '@/store/useUserStore'

export default function (ctx) {
  const { $axios, app } = ctx
  $axios.defaults.timeout = 10000
  $axios.transformRequest = [
    (data, header) => {
      if (header['Content-Type'] && header['Content-Type'].includes('json')) {
        return JSON.stringify(data)
      }
      return qs.stringify(data, { arrayFormat: 'repeat' })
    },
  ]
  $axios.onRequest((config) => {
    const userStore = useUserStore()
    const token = userStore.token
    if (token) {
      config.headers.Authorization = 'Bearer ' + token
    }
    return config
  })

  $axios.onRequestError((error) => {
    console.log('onRequestError', error)
  })

  $axios.onResponse((res) => {
    const { code, message } = res.data
    if (code !== 200) {
      app.$toast.error(message)
      return Promise.reject(res.data)
    } else {
      return res
    }

  })

  $axios.onResponseError((error) => {
    console.log('onResponseError', error)
  })

  $axios.onError((error) => {
    const { code, message } = error.response.data

    if (code === 401) {
      app.$toast.error('请先登录才能进行此操作哟！')

      const userStore = useUserStore()
      userStore.setToken('')
      userStore.setUserInfo('')
      return
    }
    if (message) {
      app.$toast.error(message)
    } else {
      app.$toast.error(error.message || '服务器出现点小问题,刷新试试吧')
    }
  })
}
